#!/bin/bash

# check_password_expiry.sh
# 功能说明:
# 1. 检查系统中所有用户或指定用户的密码到期信息。
# 2. 提供密码最后修改日期、到期日期和剩余有效天数。
# 3. 适用于定期审计用户密码状态，确保系统安全性。

# 检查单个用户的密码到期信息
check_single_user_expiry() {
  local username="$1"

  if id "$username" &>/dev/null; then
    # 使用 chage 获取用户密码信息
    local expiry_info=$(sudo chage -l "$username")
    local last_change=$(echo "$expiry_info" | grep "Last password change" | awk -F: '{print $2}' | xargs)
    local expiry_date=$(echo "$expiry_info" | grep "Password expires" | awk -F: '{print $2}' | xargs)
    local days_left=$(echo "$expiry_info" | grep "Password expires" | awk -F: '{print $2}' | xargs | xargs -I{} date -d {} +%s 2>/dev/null)

    # 当前时间戳
    local current_date=$(date +%s)
    local remaining_days=""

    if [[ "$expiry_date" == "never" ]]; then
      echo "User $username: Password does not expire."
    else
      remaining_days=$(( (days_left - current_date) / 86400 ))
      if [[ "$remaining_days" -lt 0 ]]; then
        echo "User $username: Password expired on $expiry_date."
      else
        echo "User $username: Password will expire in $remaining_days days (on $expiry_date)."
      fi
    fi
  else
    echo "User $username does not exist."
  fi
}

# 检查所有用户的密码到期信息
check_all_users_expiry() {
  echo "Checking password expiry for all users..."
  local users=$(cut -d: -f1 /etc/passwd)

  for user in $users; do
    # 忽略系统用户
    local shell=$(getent passwd "$user" | cut -d: -f7)
    if [[ "$shell" != "/sbin/nologin" && "$shell" != "/usr/sbin/nologin" && "$shell" != "/bin/false" ]]; then
      check_single_user_expiry "$user"
    fi
  done
}

# 主函数
main() {
  if [[ $# -eq 0 ]]; then
    echo "Usage: $0 [username] | --all"
    echo "  username: Check password expiry for the specified user."
    echo "  --all: Check password expiry for all users."
    exit 1
  fi

  case "$1" in
    --all)
      check_all_users_expiry
      ;;
    *)
      check_single_user_expiry "$1"
      ;;
  esac
}

# 执行主函数
main "$@"

